<?php

$query_gjj =  new query_gjj();
$query_gjj->demoRun();

define('DEV_HOST','kaifa.jianbing.com');
define('PRO_HOST','b.jianbing.com');
define('TEST_HOST','test.jianbing.com');

function element($data,$key,$def = ''){
    return array_key_exists($key,$data) ? $data[$key] : $def;
}

class query_gjj{
    public function test(){
        echo 'params='.json_encode($_REQUEST);
    }

    protected $num = 0;
    protected $headers = [
        "Content-type: application/json;charset='utf-8'",
        "Accept: application/json",
        "Cache-Control: no-cache",
        "Pragma: no-cache"
    ];
    public function __construct(){
        header('content-type:text/html;charset=utf-8');
    }
    public function demoRun(){
        error_log('m='.$_REQUEST['m']);
        $method = $_REQUEST['m'];
        $this->$method();
    }





    //密钥生成
    public function generate_Sign(&$data,$appsecret){
        $params = $data;
        ksort($params);
        $sortedstring = "";
        foreach ($params as $k => $v){
            $v = (string)$v;
            if("sign" !== $k && strlen($v) > 0){
                $sortedstring .= "$k=$v&";
            }
        }
        $sortedstring .= "appsecret=$appsecret";
        $data['sign'] = strtolower(md5($sortedstring));
    }

    public function http_request($url,$data=null,$ip=null){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//禁止sll验证提交

        if (!empty($data)) {

            curl_setopt($ch,CURLOPT_POST,1);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
        }

        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//以文档流的形式返回数据
        curl_setopt($ch,CURLOPT_HTTPHEADER,$this->headers);//以文档流的形式返回数据

        if(!empty($ip)){
            curl_setopt($ch, CURLOPT_HTTPHEADER,array("X-FORWARDED-FOR:$ip","CLIENT-IP:$ip"));//伪造ip
        }

        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }


    public function h5_get_token($uuid,$flag=true){

        $off     = element($_REQUEST,'off',false);
        $yys_cid = element($_REQUEST,'yys_cid',0);
        $version = element($_REQUEST,'vis','');
        $environment = element($_REQUEST,'env','');

        error_log('off = '.$off);
        error_log('yys_cid = '.$yys_cid);
        error_log('vis = '.$version);
        error_log('env = '.$environment);
        $secret_keys = [
            "dev"=>[
                "url"=>"kaifa.jianbing.com",
                45=>[
                    "key"=>"zwl25ryrzoo",
                    "secret"=>"tuK1yM3QQVlbSgeqnyx4w6SKgmp8Ou_e8ZGppBqqACMs_lGm",
                ],
                40=>[
                    "key"=>"dqr1djwbga3",
                    "secret"=>"8v5uj8eBnc6zDMvTGUbFpPaaV9t_XS8M-1vjfQ6Gda-Q_vCJ",
                ],
                999=>[
                    "key"=>"w69lx9zsszc",
                    "secret"=>"9lyYn4X6axkhwDqT7xzVfqNC-Wkz1QTf2q2poTHChP0LDrFK",
                ],

            ],
            "test"=>[
                "url"=>"test.jianbing.com",
                40=>[
                    "key"=>"i2gee8ejbvu",
                    "secret"=>"FkpgudX1bXZRUsbqQ8GPVRvpJqc46O0ZjS-NMXPftL3wYiRC",
                ],
                45=>[
                    "key"=>"i2gee8ejbvu",
                    "secret"=>"FkpgudX1bXZRUsbqQ8GPVRvpJqc46O0ZjS-NMXPftL3wYiRC",
                ]
            ],
            "pro"=>[
                "url"=>"b.jianbing.com",
                //我来贷,生产
                45=>[
                    "key"=>"yuecg2kync0",
                    "secret"=>"yjpYCfKegawYF0OGgS-VOTpokN92tD1_TXUJ-G1gWDayG21T",
                ],
                //宁波银行，生产
                40=>[
                    "key"=>"dcrrj4tug11",
                    "secret"=>"74609L8zs39Ky6wnD5tSq6CfoO6evvZetMyioARCZIrh8IJK",
                ],
            ],
        ];
        //环境选着
        $env_info  = $secret_keys[$environment];
        $url       = $env_info['url'];
        $appkey    = $env_info[$yys_cid]['key'];
        $appsecret = $env_info[$yys_cid]['secret'];


        $salt = $appsecret;//密钥


        switch ($version){
            case 'hs':
                $url = $url."/ds/gjj/v2/get_access_token";

                $data = ['timestamp'=>time(),'appkey'=>$appkey,'uuid'=>$uuid];
                $this->generate_Sign($data,$salt);

                $result = $this->http_json_request($url,$data);
                return $result['data'];
                error_log('in');
                break;
            case 'pc':
                $data = ['timestamp'=>time(),'appkey'=>$appkey,'passport'=>$uuid];
                $this->generate_Sign($data,$salt);

                $url = $url."/h5/api.php?timestamp={$data['timestamp']}&appkey={$data['appkey']}&passport={$data['passport']}&sign={$data['sign']}";
                //timestamp={$data['timestamp']}&appkey={$data['appkey']}&passport={$data['passport']}&sign={$data['sign']}
                $result = $this->http_request($url,$data);

                error_log('get_token_url='.json_encode($url));
                error_log('data='.json_encode($result));

                if(gettype($result)==='string'){
                    if($ret = json_decode($result,true)){
                        if(isset($ret['data']) && $ret['errcode']==0){
                            return $ret['data'];
                        }
                        exit(json_encode($result));

                    };
                }
                return $result;
                break;
            case 'h5':
                $data = ['timestamp'=>time(),'appkey'=>$appkey,'passport'=>$uuid];
                $this->generate_Sign($data,$salt);
//            echo json_encode($data);

                $url = $url."/h5/api.php?timestamp={$data['timestamp']}&appkey={$data['appkey']}&passport={$data['passport']}&sign={$data['sign']}";
                //timestamp={$data['timestamp']}&appkey={$data['appkey']}&passport={$data['passport']}&sign={$data['sign']}
                $result = $this->http_request($url,$data);

                error_log('get_token_url='.json_encode($url));
                error_log('data='.json_encode($result));

                if(gettype($result)==='string'){
                    if($ret = json_decode($result,true)){
                        if(isset($ret['data']) && $ret['errcode']==0){
                            return $ret['data'];
                        }
                        exit(json_encode($result));

                    };
                }
                return $result;
                break;
            default :
                return false;
        }
    }

    public function http_json_request($url,$data){
        $json_data = json_encode($data);
        $json_data = $this->http_request($url,$json_data);

        return json_decode($json_data,true);
    }

    public function var_dump($result){
        echo '<pre />';
        var_dump($result);
        exit;
    }

    public function query_jdq(){
        $off = 1;

        if($off){//生产
            $appkey = 'yxqzz8zjfxv';
            $appsecret = 'BepLss0hdQChXK0awWReYX_oNvmwTpCL9cqhoeuBzk87-5he';
            $url = 'http://api.jianbing.com/api.php';
        }else{//开发
            $appkey = 'yxqzz8zjfxv';
            $appsecret = 'BepLss0hdQChXK0awWReYX_oNvmwTpCL9cqhoeuBzk87-5he';
            $url = 'http://kaifa.jianbing.com/api/api.php';
        }

        $time = time();
        $uuid = $_POST['passport'];
        $gjj_sid = $_POST['gjj_sid'];
        $yys_cid = $_POST['yys_cid'];

        $ip_arr = [
            '51'=>'183.128.167.77',
            '10'=>'220.191.34.153'
        ];

        if($off){
            $ip_arr = [
                '51'=>'183.128.167.76',
                '10'=>'220.191.34.153',
                '45'=>'121.201.7.189',
                '11'=>'122.224.130.226'
            ];
        }

        if(!isset($yys_cid)) {
            echo "填写yys_cid";
            exit;
        }
        $ip = $ip_arr[$yys_cid];
        $d = [
            'f'=>'jbLoadUserGjjs',
            'yys_cid'=>51,
            'passport'=>$uuid,
            'gjj_sid'=>$gjj_sid,
            'appkey'=>$appkey,
            't'=>$time
        ];
        $data = [];

        $data['s'] = $this->generate_return_Sign($d,$appsecret);//添加
        $data['t'] = $time;
        $data['d'] = json_encode($d);

        $url = <<<EOT
http://kaifa.jianbing.com/api/api.php?s={$data['s']}&t={$data['t']}&d={$data['d']}
EOT;
        if($off){
            $url = <<<EOT
http://api.jianbing.com/api.php?s={$data['s']}&t={$data['t']}&d={$data['d']}
EOT;
        }

        $result = $this->http_request($url,null,$ip);
        echo $result;
    }

    public function generate_return_Sign($data,$appsecret){
        $params = $data;
        ksort($params);
        $sortedstring = "";
        foreach ($params as $k => $v){
            $v = (string)$v;
            if("sign" !== $k && strlen($v) > 0){
                $sortedstring .= "$k=$v&";
            }
        }
        $sortedstring .= "appsecret=$appsecret";
        return strtolower(md5($sortedstring));
    }

    public function send_WLD(){


        $off = isset($_POST['off'])?$_POST['off']:0;
        $yys_cid = isset($_POST['yys_cid'])?$_POST['yys_cid']:10;
        $uuid = $_POST['passport'];
        $shebao_sid = $_POST['shebao_sid'];


        $off = 1;
        error_log('$off'.$off);
        error_log('$uuid'.$uuid);
        error_log('$shebao_sid'.$shebao_sid);

        echo $off;
        if($off){
            $appkey = 'yuecg2kync0';
            $appsecret = 'yjpYCfKegawYF0OGgS-VOTpokN92tD1_TXUJ-G1gWDayG21T';
            $url = 'http://b.jianbing.com/ds/shebao/v1/get_user_shebao?debug';

        }else{

            $appkey = 'zwl25ryrzoo';
            $appsecret = 'tuK1yM3QQVlbSgeqnyx4w6SKgmp8Ou_e8ZGppBqqACMs_lGm';
            $url = 'http://kaifa.jianbing.com/ds/shebao/v1/get_user_shebao?debug';
        }

        $time = time();

        $data = ['appkey'=>$appkey,'timestamp'=>$time,'shebao_sid'=>$shebao_sid,'uuid'=>$uuid];

        $this->generate_Sign($data,$appsecret);//添加

        $result = $this->http_request($url,json_encode($data));

        $this->var_dump($result);
    }

    //API公积金数据拉取
    public function get_gjj(){

        $off = isset($_POST['off'])?$_POST['off']:0;
        error_log('off='.$off);
        $yys_cid = isset($_POST['yys_cid'])?$_POST['yys_cid']:10;
        $fun = isset($_POST['f'])?$_POST['f']:'jbLoadUserGjjs';//默认方法
        $env = isset($_POST['env'])?$_POST['env']:'dev';//默认方法

        error_log($fun);


        //ip白名单模仿
        $ip_arr = [
            '51'=>'183.128.167.76',
            '10'=>'220.191.34.153',
            '999'=>'122.225.218.30',
            '40'=>"22.22.22.22",
            '45'=>"121.201.87.36",
            '2'=>"220.191.35.99",
            '16'=>"221.136.68.109",
        ];

        $ip = $ip_arr[$yys_cid];

        if($env=='pro'){

            $url = 'api.jianbing.com/api.php';

            //生产,借点钱
            $appkey = 'dqr1djwbga3';
            $appsecret = '8v5uj8eBnc6zDMvTGUbFpPaaV9t_XS8M-1vjfQ6Gda-Q_vCJ';

            //生产，宁波
            $appkey = 'dcrrj4tug11';
            $appsecret = '74609L8zs39Ky6wnD5tSq6CfoO6evvZetMyioARCZIrh8IJK';

            //生产,中原银行
            //$appkey = 'ykcdekk1sjy';
            //$appsecret = 'zd45JLCQmKQrp-o4gqYKWnjdsCKe61zmbei6slUD0B5SBJZ8';

            //生产,我来贷
            //$appkey = 'ykcdekk1sjy';
            //$appsecret = 'zd45JLCQmKQrp-o4gqYKWnjdsCKe61zmbei6slUD0B5SBJZ8';

        }else{
            //开发，宁波
            $appkey = 'dqr1djwbga3';
            $appsecret = '8v5uj8eBnc6zDMvTGUbFpPaaV9t_XS8M-1vjfQ6Gda-Q_vCJ';
            $url = 'http://kaifa.jianbing.com/api/api.php';

            //测试
            //$appkey = 'i2gee8ejbvu';
            //$appsecret = 'FkpgudX1bXZRUsbqQ8GPVRvpJqc46O0ZjS-NMXPftL3wYiRC';
            //$url = "http://test.jianbing.com/hs/opensb/query?openid=$openid&token=$token&notify_url=http://xa.wolaidai.com:9030/tools/shebao51callback&return_url=https://webapp.wolaidai.com/auth/shebao";
            //$url = "http://test.jianbing.com/api/api.php?d=";

        }
        $time = time();
        $uuid = $_POST['passport'];
        $shebao_sid = $_POST['shebao_sid'];
        $gjj_sid = $_POST['gjj_sid'];

//        $data = ['appkey'=>$appkey,'timestamp'=>$time,'shebao_sid'=>$shebao_sid,'uuid'=>$uuid];
//        $data = ['appkey'=>$appkey,'timestamp'=>$time,'gjj_sid'=>$gjj_sid,'passport'=>$uuid,'f'=>'jbGetGjjDetails'];

        error_log($yys_cid);
        if($yys_cid==2){
            if($off){
                $url = 'api.jianbing.com/api51NB.php';
            }else{
                $url = 'kaifa.jianbing.com/api/api51NB.php';
            }

            $ip = '183.129.207.194';
            $data = [
                'appkey'=>$appkey,
                't'=>$time,
                'd'=> [
                    'f'=>'jbGetGjjDetails',
                    'gjj_sid'=>$gjj_sid,
                    'passport'=>$uuid
                ],
            ];


            $data['d'] = json_encode($data['d']);
            $salt = 'eG^Tqj7nPPWHVxl%';
            $data['s'] = md5($data['d'] . $time . $salt);


            error_log(print_r($data,true));
            error_log('urlA = '+$url);
            $result = $this->http_request($url,$data,$ip);
//        $result = $this->http_request($url,json_encode($data),$ip);

            $this->var_dump($result);

        }else{
            error_log('urlB = '.$url);
            $data = [
                'appkey'=>$appkey,
                'time'=>$time,
                'gjj_sid'=>$gjj_sid,
                'passport'=>$uuid,
                'f'=>$fun,
            ];

            $this->generate_Sign($data,$appsecret);//添加
            $data = json_encode($data);

            $url = $url."?d=$data";

            $result = $this->http_request($url,null,$ip);
//        $result = $this->http_request($url,json_encode($data),$ip);

            $this->var_dump($result);

        }

    }

    //获取token
    public function open_shebao(){
        $uuid    = element($_REQUEST,'uuid','');
        $off     = element($_REQUEST,'off',false);
        $yys_cid = element($_REQUEST,'yys_cid',false);
        $version = element($_REQUEST,'vis',false);
        $redirect = element($_REQUEST,'redirect','');
        $env = element($_REQUEST,'env','');

        $token_result = $this->h5_get_token($uuid);

        $openid =  $token_result['openid'];
        $token =  $token_result['token'];

        switch($env){
            case 'dev':
                $redirect_url = "http://kaifa.jianbing.com/hs/opensb/query?openid=$openid&token=$token&notify_url=http://kaifa.jianbing.com/ds/help_page/callback_confirm&return_url=https://webapp.wolaidai.com/auth/shebao";
                break;
            case 'test':
                $redirect_url = "http://test.jianbing.com/hs/opensb/query?openid=$openid&token=$token&notify_url=http://kaifa.jianbing.com/ds/help_page/callback_confirm&return_url=https://webapp.wolaidai.com/auth/shebao";
                //$redirect_url = "http://120.26.118.241/hs/opensb/query?openid=$openid&token=$token&notify_url=http://kaifa.jianbing.com/ds/help_page/callback_confirm&return_url=https://webapp.wolaidai.com/auth/shebao";
                break;
            case 'pro':
                $redirect_url = "http://b.jianbing.com/hs/opensb/query?openid=$openid&token=$token&notify_url=http://kaifa.jianbing.com/ds/help_page/callback_confirm&return_url=https://webapp.wolaidai.com/auth/shebao";
                break;
        }

        echo $redirect_url.'&redirect='.$redirect;
        error_log('url='.$redirect_url);
        exit;
    }

    public function send_h5(){

    }

    public function get_user_gjj(){
        $appkey = 'NitPUFY5bG9acDZHSTUwa1NyYy9nQT09';
        $appsecret = 'UWNGSU1jbEVMSHd2SGtra24rQnp6VXhXNzhuWDhqWGZyb1YxWjZ1ZjArUT0=';
        $url = 'http://b.jianbing.com/ds/gjj/v2/get_user_gjj';

//        $appkey = 'k8v4nztfv2r';
//        $appsecret = 'It8d0pJWuUMsF6Jf5cjZjcce9Rkmyifr9kL6EmOmcND-Tzg0';
//        $url = 'http://kaifa.jianbing.com/ds/gjj/v2/get_user_gjj';

        $time = time();
        $uuid = $_POST['uuid'];
        $gjj_sid = $_POST['gjj_sid'];

        $data = ['appkey'=>$appkey,'timestamp'=>$time,'uuid'=>$uuid,'gjj_sid'=>$gjj_sid];
        $this->generate_Sign($data,$appsecret);//添加

        $result = $this->http_request($url,json_encode($data));

        $this->var_dump($result);
    }

    public function notify(){
        $data = $_REQUEST;
        $this->var_dump($data);
    }

    public function sxgjjreg () {
        $html = $this->curl_get_contents("https://115.239.233.150:9090/wt/jcrzc");
        error_log($html);
        echo $html;
        exit;
    }

    public function curl_get_contents($url, array $post_data = array(), $verbose = false, $ref_url = false, $cookie_location = false, $return_transfer = true)
    {
        $request_starttime = microtime(true);
        $return_val = false;

        $ssl = false;
        if (stripos($url, 'https://') === 0) {
            $ssl = true;
        }

        $pointer = curl_init();

        curl_setopt($pointer, CURLOPT_URL, $url);
        curl_setopt($pointer, CURLOPT_TIMEOUT, 40);
        curl_setopt($pointer, CURLOPT_RETURNTRANSFER, $return_transfer);
        curl_setopt($pointer, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.28 Safari/534.10");
        if ($ssl) {
            curl_setopt($pointer, CURLOPT_SSL_VERIFYHOST, 2);
            curl_setopt($pointer, CURLOPT_SSL_VERIFYPEER, 0);
        } else {
            curl_setopt($pointer, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($pointer, CURLOPT_SSL_VERIFYPEER, false);
        }
        curl_setopt($pointer, CURLOPT_HEADER, false);
        curl_setopt($pointer, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($pointer, CURLOPT_AUTOREFERER, true);

        if ($cookie_location !== false) {
            curl_setopt($pointer, CURLOPT_COOKIEJAR, $cookie_location);
            curl_setopt($pointer, CURLOPT_COOKIEFILE, $cookie_location);
//		curl_setopt($pointer, CURLOPT_COOKIE, session_name() . '=' . session_id());
        }
    }

}